package simpleim

import (
	"encoding/json"
	"github.com/IBM/sarama"
	"github.com/gorilla/websocket"
	"log"
)

type ConsumerHandler struct {
	store *ConnStore
}

func (c *ConsumerHandler) Setup(session sarama.ConsumerGroupSession) error {
	log.Println("Setup...")
	return nil
}

func (c *ConsumerHandler) Cleanup(session sarama.ConsumerGroupSession) error {
	log.Println("Cleanup...")
	return nil
}

func (c *ConsumerHandler) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
	messages := claim.Messages()
	for msg := range messages {
		var event Event
		err := json.Unmarshal(msg.Value, &event)
		if err != nil {
			log.Printf("<UNK>:%v", err)
			continue
		}
		// 发送给接收者
		conn, err := c.store.Load(event.Receiver)
		if err != nil {
			log.Printf("<UNK>:%v", err)
			continue
		}
		conn.WriteMessage(websocket.TextMessage, []byte(event.Msg.Content))
	}
	return nil
}
